<template>
    <div class="sensitive-filter">
        <div class="page-header">
            <h2>敏感词过滤</h2>
            <div class="description">
                配置敏感词列表和过滤规则，自动删除或警告包含敏感词的消息
            </div>
        </div>

        <!-- 群组选择与功能开关 -->
        <el-card class="settings-card">
            <div class="settings-header">
                <div class="group-select">
                    <span class="label">当前群组:</span>
                    <el-select v-model="form.groupId" placeholder="请选择要管理的群组" style="width: 250px"
                        @change="loadSettings">
                        <el-option v-for="group in groupList" :key="group.groupId" :label="group.name"
                            :value="group.groupId" />
                    </el-select>
                </div>
                <div class="feature-switch">
                    <span class="label">功能状态:</span>
                    <el-switch v-model="form.enabled" @change="saveSettings" />
                    <span class="status-text">{{ form.enabled ? '已启用' : '已禁用' }}</span>
                </div>
            </div>
        </el-card>

        <div v-if="form.groupId && form.enabled" class="filter-content">
            <!-- 过滤规则设置 -->
            <el-card class="rule-card">
                <template #header>
                    <div class="card-header">
                        <span>过滤规则</span>
                    </div>
                </template>

                <el-form :model="form" label-width="120px">
                    <el-form-item label="过滤动作">
                        <el-radio-group v-model="form.action">
                            <el-radio label="delete">删除消息</el-radio>
                            <el-radio label="warn">发出警告</el-radio>
                            <el-radio label="both">删除并警告</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="违规记分">
                        <el-input-number v-model="form.penaltyPoints" :min="0" :max="100" />
                        <span class="option-help">违规一次扣除的积分</span>
                    </el-form-item>

                    <el-form-item label="自动禁言">
                        <el-switch v-model="form.autoBan" />
                        <span class="option-help">多次违规自动禁言</span>
                    </el-form-item>

                    <el-form-item v-if="form.autoBan" label="违规次数阈值">
                        <el-input-number v-model="form.banThreshold" :min="1" :max="10" />
                        <span class="option-help">达到多少次违规触发禁言</span>
                    </el-form-item>

                    <el-form-item v-if="form.autoBan" label="禁言时长">
                        <el-input-number v-model="form.banDuration" :min="1" :max="72" />
                        <span class="option-help">禁言小时数</span>
                    </el-form-item>

                    <el-form-item label="过滤外部链接">
                        <el-switch v-model="form.filterLinks" />
                        <span class="option-help">启用后将自动过滤所有外部链接，包括HTTP链接、t.me链接等</span>
                    </el-form-item>

                    <el-form-item v-if="form.filterLinks" label="链接白名单">
                        <el-tag v-for="domain in form.whitelistDomains" :key="domain" closable
                            @close="handleRemoveDomain(domain)" class="domain-tag">
                            {{ domain }}
                        </el-tag>
                        <el-input v-if="inputDomainVisible" ref="domainInputRef" v-model="inputDomainValue"
                            class="ml-1 w-20" size="small" @keyup.enter="handleAddDomain" @blur="handleAddDomain" />
                        <el-button v-else class="button-new-tag ml-1" size="small" @click="showDomainInput">
                            + 添加域名
                        </el-button>
                        <div class="domain-help">
                            添加允许的域名，如：<el-link type="primary"
                                @click="quickAddDomain('telegram.org')">telegram.org</el-link>、
                            <el-link type="primary" @click="quickAddDomain('t.me')">t.me</el-link>、
                            example.com（不含http://和www.）
                        </div>
                        <div class="domain-tip">
                            <i class="el-icon-info"></i>
                            添加 <code>t.me</code> 或 <code>telegram.org</code> 将允许所有Telegram内部链接
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="saveSettings">保存设置</el-button>
                        <el-button @click="resetSettings">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <!-- 敏感词管理 -->
            <el-card class="word-list-card">
                <template #header>
                    <div class="card-header">
                        <span>敏感词管理</span>
                        <div class="header-actions">
                            <el-button type="primary" @click="showBatchImportDialog">批量导入</el-button>
                            <el-button type="primary" @click="showAddDialog">添加敏感词</el-button>
                        </div>
                    </div>
                </template>

                <div class="word-categories">
                    <el-radio-group v-model="currentCategory" class="category-tabs">
                        <el-radio-button label="all">全部敏感词</el-radio-button>
                        <el-radio-button label="custom">自定义词库</el-radio-button>
                        <el-radio-button label="politics">政治敏感</el-radio-button>
                        <el-radio-button label="porn">色情低俗</el-radio-button>
                        <el-radio-button label="spam">广告推销</el-radio-button>
                    </el-radio-group>
                </div>

                <div class="search-bar">
                    <el-input v-model="searchKeyword" placeholder="搜索敏感词" clearable prefix-icon="Search">
                        <template #append>
                            <el-button @click="searchWords">搜索</el-button>
                        </template>
                    </el-input>
                </div>

                <el-table :data="filteredWords" border style="width: 100%" v-loading="tableLoading">
                    <el-table-column prop="word" label="敏感词" min-width="150">
                        <template #default="{ row }">
                            <span class="sensitive-word">{{ row.word }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="category" label="分类" width="120">
                        <template #default="{ row }">
                            <el-tag :type="getCategoryTag(row.category)">
                                {{ getCategoryName(row.category) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="matchType" label="匹配方式" width="120">
                        <template #default="{ row }">
                            {{ row.matchType === 'exact' ? '精确匹配' : '模糊匹配' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="创建时间" width="180" />
                    <el-table-column label="操作" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button type="danger" size="small" @click="deleteWord(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" :total="totalWords"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <div v-else-if="form.groupId && !form.enabled" class="feature-disabled">
            <el-empty description="敏感词过滤功能已禁用，请先启用功能">
                <el-button type="primary" @click="form.enabled = true; saveSettings()">立即启用</el-button>
            </el-empty>
        </div>

        <div v-else class="empty-placeholder">
            <el-empty description="请先选择要管理的群组" />
        </div>

        <!-- 添加敏感词弹窗 -->
        <el-dialog v-model="addDialogVisible" title="添加敏感词" width="500px">
            <el-form :model="newWord" label-width="100px" :rules="addRules" ref="addFormRef">
                <el-form-item label="敏感词" prop="word">
                    <el-input v-model="newWord.word" placeholder="请输入敏感词" />
                </el-form-item>

                <el-form-item label="分类" prop="category">
                    <el-select v-model="newWord.category" placeholder="请选择分类">
                        <el-option label="自定义词库" value="custom" />
                        <el-option label="政治敏感" value="politics" />
                        <el-option label="色情低俗" value="porn" />
                        <el-option label="广告推销" value="spam" />
                    </el-select>
                </el-form-item>

                <el-form-item label="匹配方式" prop="matchType">
                    <el-radio-group v-model="newWord.matchType">
                        <el-radio label="exact">精确匹配</el-radio>
                        <el-radio label="fuzzy">模糊匹配</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addWord">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加批量导入对话框 -->
        <batch-import-dialog v-model:visible="batchImportDialogVisible" :groupId="form.groupId"
            @import-success="handleBatchImport" />
    </div>
</template>

<script>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGroups } from '../../../api/group'
import {
    getSensitiveWordSettings,
    updateSensitiveWordSettings,
    getSensitiveWords,
    addSensitiveWord,
    deleteSensitiveWord,
    batchImportSensitiveWords
} from '../../../api/sensitiveWord'
import BatchImportDialog from './components/BatchImportDialog.vue'

export default {
    name: 'SensitiveFilter',
    components: {
        BatchImportDialog
    },
    setup() {
        const route = useRoute()
        const addFormRef = ref(null)

        // 表单数据
        const form = reactive({
            groupId: route.query.groupId || '',
            enabled: false,
            action: 'delete',
            penaltyPoints: 5,
            autoBan: false,
            banThreshold: 3,
            banDuration: 24,
            filterLinks: false,
            whitelistDomains: []
        })

        // 群组数据
        const groupList = ref([])
        const loading = ref(false)

        // 敏感词列表数据
        const sensitiveWords = ref([])
        const tableLoading = ref(false)
        const currentCategory = ref('all')
        const searchKeyword = ref('')
        const currentPage = ref(1)
        const pageSize = ref(10)
        const totalWords = ref(0)

        // 添加敏感词
        const addDialogVisible = ref(false)
        const newWord = reactive({
            word: '',
            category: 'custom',
            matchType: 'exact'
        })

        // 表单验证规则
        const addRules = {
            word: [
                { required: true, message: '请输入敏感词', trigger: 'blur' },
                { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
            ],
            category: [
                { required: true, message: '请选择分类', trigger: 'change' }
            ],
            matchType: [
                { required: true, message: '请选择匹配方式', trigger: 'change' }
            ]
        }

        // 过滤后的敏感词
        const filteredWords = computed(() => {
            if (currentCategory.value === 'all' && !searchKeyword.value) {
                return sensitiveWords.value
            }

            let result = sensitiveWords.value

            if (currentCategory.value !== 'all') {
                result = result.filter(word => word.category === currentCategory.value)
            }

            if (searchKeyword.value) {
                result = result.filter(word => word.word.includes(searchKeyword.value))
            }

            return result
        })

        // 链接白名单
        const inputDomainVisible = ref(false);
        const inputDomainValue = ref('');
        const domainInputRef = ref(null);

        const showDomainInput = () => {
            inputDomainVisible.value = true;
            nextTick(() => {
                domainInputRef.value.focus();
            });
        };

        const handleAddDomain = () => {
            const domain = inputDomainValue.value.trim();
            if (domain) {
                // 简单的域名验证
                const domainRegex = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i;
                if (!domainRegex.test(domain)) {
                    ElMessage.warning('请输入有效的域名，如：example.com');
                    return;
                }

                if (!form.whitelistDomains.includes(domain)) {
                    form.whitelistDomains.push(domain);
                } else {
                    ElMessage.info('该域名已在白名单中');
                }
            }
            inputDomainVisible.value = false;
            inputDomainValue.value = '';
        };

        // 新增快速添加常用域名方法
        const quickAddDomain = (domain) => {
            if (!form.whitelistDomains.includes(domain)) {
                form.whitelistDomains.push(domain);
                ElMessage.success(`已添加 ${domain} 到白名单`);
            } else {
                ElMessage.info('该域名已在白名单中');
            }
        };

        const handleRemoveDomain = (domain) => {
            form.whitelistDomains = form.whitelistDomains.filter(d => d !== domain);
        };

        // 获取群组列表
        const fetchGroups = async () => {
            loading.value = true
            try {
                const res = await getGroups()
                if (res.data.success) {
                    groupList.value = res.data.data
                } else {
                    ElMessage.error(res.data.message || '获取群组失败')
                }
            } catch (error) {
                console.error('获取群组失败:', error)
                ElMessage.error('获取群组失败')
            } finally {
                loading.value = false
            }
        }

        // 加载敏感词设置
        const loadSettings = async (groupId) => {
            if (!groupId) return

            loading.value = true
            try {
                const res = await getSensitiveWordSettings(groupId)
                if (res.data.success) {
                    const settings = res.data.data
                    form.enabled = settings.enabled
                    form.action = settings.action
                    form.penaltyPoints = settings.penaltyPoints
                    form.autoBan = settings.autoBan
                    form.banThreshold = settings.banThreshold
                    form.banDuration = settings.banDuration
                    form.filterLinks = settings.filterLinks
                    form.whitelistDomains = settings.whitelistDomains || []
                } else {
                    ElMessage.error(res.data.message || '获取设置失败')
                }
            } catch (error) {
                console.error('获取设置失败:', error)
                ElMessage.error('获取设置失败')
            } finally {
                loading.value = false
            }

            // 加载敏感词列表
            loadSensitiveWords()
        }

        // 加载敏感词列表
        const loadSensitiveWords = async () => {
            if (!form.groupId) return

            tableLoading.value = true
            try {
                const res = await getSensitiveWords(form.groupId, {
                    page: currentPage.value,
                    limit: pageSize.value,
                    category: currentCategory.value !== 'all' ? currentCategory.value : undefined,
                    search: searchKeyword.value || undefined
                })

                if (res.data.success) {
                    sensitiveWords.value = res.data.data.list
                    totalWords.value = res.data.data.total
                } else {
                    ElMessage.error(res.data.message || '获取敏感词列表失败')
                }
            } catch (error) {
                console.error('获取敏感词列表失败:', error)
                ElMessage.error('获取敏感词列表失败')
            } finally {
                tableLoading.value = false
            }
        }

        // 保存设置
        const saveSettings = async () => {
            if (!form.groupId) {
                ElMessage.warning('请先选择群组')
                return
            }

            loading.value = true
            try {
                const res = await updateSensitiveWordSettings(form.groupId, {
                    enabled: form.enabled,
                    action: form.action,
                    penaltyPoints: form.penaltyPoints,
                    autoBan: form.autoBan,
                    banThreshold: form.banThreshold,
                    banDuration: form.banDuration,
                    filterLinks: form.filterLinks,
                    whitelistDomains: form.whitelistDomains
                })

                if (res.data.success) {
                    ElMessage.success(res.data.message || '设置保存成功')
                } else {
                    ElMessage.error(res.data.message || '设置保存失败')
                }
            } catch (error) {
                console.error('保存设置失败:', error)
                ElMessage.error('保存设置失败')
            } finally {
                loading.value = false
            }
        }

        // 重置设置
        const resetSettings = () => {
            form.action = 'delete'
            form.penaltyPoints = 5
            form.autoBan = false
            form.banThreshold = 3
            form.banDuration = 24
            form.filterLinks = false
            form.whitelistDomains = []
            ElMessage.info('设置已重置')
        }

        // 分页相关
        const handleSizeChange = (val) => {
            pageSize.value = val
            loadSensitiveWords()
        }

        const handleCurrentChange = (val) => {
            currentPage.value = val
            loadSensitiveWords()
        }

        // 搜索敏感词
        const searchWords = () => {
            currentPage.value = 1
            loadSensitiveWords()
        }

        // 获取分类名称
        const getCategoryName = (category) => {
            const categoryMap = {
                'custom': '自定义词库',
                'politics': '政治敏感',
                'porn': '色情低俗',
                'spam': '广告推销'
            }
            return categoryMap[category] || '未知分类'
        }

        // 获取分类标签类型
        const getCategoryTag = (category) => {
            const tagMap = {
                'custom': '',
                'politics': 'danger',
                'porn': 'warning',
                'spam': 'info'
            }
            return tagMap[category] || ''
        }

        // 显示添加对话框
        const showAddDialog = () => {
            newWord.word = ''
            newWord.category = 'custom'
            newWord.matchType = 'exact'
            addDialogVisible.value = true
        }

        // 添加敏感词
        const addWord = async () => {
            addFormRef.value.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await addSensitiveWord({
                            word: newWord.word,
                            groupId: form.groupId,
                            category: newWord.category,
                            matchType: newWord.matchType
                        })

                        if (res.data.success) {
                            ElMessage.success(res.data.message || '添加成功')
                            addDialogVisible.value = false
                            loadSensitiveWords()
                        } else {
                            ElMessage.error(res.data.message || '添加失败')
                        }
                    } catch (error) {
                        console.error('添加敏感词失败:', error)
                        ElMessage.error('添加敏感词失败')
                    }
                }
            })
        }

        // 删除敏感词
        const deleteWord = (row) => {
            ElMessageBox.confirm(`确认删除敏感词"${row.word}"吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await deleteSensitiveWord(row._id)
                    if (res.data.success) {
                        ElMessage.success(res.data.message || '删除成功')
                        loadSensitiveWords()
                    } else {
                        ElMessage.error(res.data.message || '删除失败')
                    }
                } catch (error) {
                    console.error('删除敏感词失败:', error)
                    ElMessage.error('删除敏感词失败')
                }
            }).catch(() => { })
        }

        // 批量导入对话框
        const batchImportDialogVisible = ref(false)

        // 显示批量导入对话框
        const showBatchImportDialog = () => {
            if (!form.groupId) {
                ElMessage.warning('请先选择群组')
                return
            }
            batchImportDialogVisible.value = true
        }

        // 处理批量导入
        const handleBatchImport = async (data) => {
            try {
                loading.value = true
                const res = await batchImportSensitiveWords({
                    words: data.words,
                    groupId: data.groupId,
                    category: data.category,
                    matchType: data.matchType
                })

                if (res.data.success) {
                    ElMessage.success(`成功导入 ${res.data.data.totalImported} 个敏感词`)
                    loadSensitiveWords()
                } else {
                    ElMessage.error(res.data.message || '批量导入失败')
                }
            } catch (error) {
                console.error('批量导入敏感词失败:', error)
                ElMessage.error('批量导入敏感词失败')
            } finally {
                loading.value = false
            }
        }

        // 初始化
        onMounted(() => {
            fetchGroups()
            if (form.groupId) {
                loadSettings(form.groupId)
            }
        })

        return {
            form,
            groupList,
            loading,
            sensitiveWords,
            filteredWords,
            tableLoading,
            currentCategory,
            searchKeyword,
            currentPage,
            pageSize,
            totalWords,
            addDialogVisible,
            newWord,
            addRules,
            addFormRef,
            inputDomainVisible,
            inputDomainValue,
            domainInputRef,
            showDomainInput,
            handleAddDomain,
            handleRemoveDomain,
            quickAddDomain,

            loadSettings,
            saveSettings,
            resetSettings,
            handleSizeChange,
            handleCurrentChange,
            searchWords,
            getCategoryName,
            getCategoryTag,
            showAddDialog,
            addWord,
            deleteWord,
            batchImportDialogVisible,
            showBatchImportDialog,
            handleBatchImport
        }
    }
}
</script>

<style scoped>
.sensitive-filter {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
}

.page-header h2 {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 10px;
}

.description {
    color: #666;
    font-size: 14px;
}

.settings-card {
    margin-bottom: 20px;
}

.settings-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.group-select,
.feature-switch {
    display: flex;
    align-items: center;
}

.label {
    font-weight: 500;
    margin-right: 10px;
}

.status-text {
    margin-left: 10px;
    font-size: 14px;
}

.filter-content {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.option-help {
    margin-left: 10px;
    font-size: 13px;
    color: #666;
}

.word-categories {
    margin-bottom: 20px;
}

.search-bar {
    margin-bottom: 20px;
}

.sensitive-word {
    color: #f56c6c;
    font-weight: 500;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.empty-placeholder,
.feature-disabled {
    margin-top: 50px;
    text-align: center;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.domain-tag {
    margin-right: 6px;
    margin-bottom: 6px;
}

.domain-help {
    font-size: 12px;
    color: #909399;
    margin-top: 6px;
}

.ml-1 {
    margin-left: 8px;
}

.w-20 {
    width: 200px;
}

.domain-tip {
    font-size: 12px;
    color: #67c23a;
    margin-top: 4px;
    padding: 4px 8px;
    background-color: #f0f9eb;
    border-radius: 4px;
    display: flex;
    align-items: center;
}

.domain-tip code {
    background-color: #f8f8f8;
    padding: 0 4px;
    border-radius: 3px;
    margin: 0 2px;
    font-family: monospace;
}

@media (max-width: 1200px) {
    .filter-content {
        grid-template-columns: 1fr;
    }
}
</style>